#include "slist.h"

/**
 * this function will initiaize the specified single list
 * @param sl: the pointer of single list node
 * @return: void
 */
void mx_slist_init (mx_slist_pt sl)
{
    sl->next = sl;
}

/**
 * this function will insert the single list before the base
 * @param tsl: the pointer of target single list
 * @param sl: the pointer of single list to be insert
 * @return: void
 */
void mx_slist_insert_before (mx_slist_pt tsl, mx_slist_pt sl)
{
    mx_slist_pt pnext, pbefore = mx_null;
    for (pnext = sl->next; pnext != sl; pnext = pnext->next)
    {
        pbefore = pnext;
    }
    if (pbefore)
    {
        pbefore->next = sl;
        sl->next = tsl;
    }
    else
    {
        tsl->next = sl;
        sl->next = tsl;
    }
}

/**
 * this function will insert the single list after the base
 * @param tsl: the pointer of target single list
 * @param sl: the pointer of single list to be insert
 * @return: void
 */
void mx_slist_insert_after (mx_slist_pt tsl, mx_slist_pt sl)
{
    sl->next = tsl->next;
    tsl->next = sl;
}

/**
 * this function will remove the specified single list node
 * @param sl: the pointer of single list to be remove
 * @return: void
 */
void mx_slist_remove (mx_slist_pt sl)
{
    mx_slist_pt pnext, pbefore = mx_null;
    for (pnext = sl->next; pnext != sl; pnext = pnext->next)
    {
        pbefore = pnext;
    }
    if (pbefore)
    {
        pbefore->next = sl->next;
    }
}

/**
 * this function will return the length of specified single list
 * @param sl: this pointer of single list
 * @return: the length of single list
 */
mx_usize_t mx_slist_count (mx_slist_pt sl)
{
    mx_usize_t ret = 0;
    mx_slist_foreach(sl, l, {
        ret ++;
    });
    return ret;
}
